﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Windows.Forms;
using ApplicationLibrary;
using ApplicationLibrary.DBManager;
using ApplicationLibrary.ExtendedControls;
using ApplicationLibrary.Preferences;
using ApplicationLibrary.SqlConnector;
using Plumber.Accounting.Preferences;
using Plumber.Masters.Library;
using Plumber.Masters.ModuleData;

namespace Plumber.Masters.Forms
{
    public partial class Masters : DocumentForm
    {
        private CheckDuplicateTaxNo CheckFiscalTaxCode;
        private const string PRINT_ENVELOPE = "PRINT_ENVELOPE";
        private const string SEND_MAIL = "SEND_MAIL";

        private const string CondominSlave = "CONDOMINIUMSLAVE";
        private DRMasterTypeByType dRMasterTypeByType;
        private PreferencesManager<AccountingPref> myAccountingPref = null;
        private AccountingPref AccountingPref = null;
        private ComboBoxManager cbbTaxCodeManager = null;
        private ComboBoxManager cbbRestraintManager = null;
        private RRTaxCode rRTaxCode = null;
        private string condomType = string.Empty;
        private bool isCondominium = false;
        private bool isAdministrator = false;
        private bool CanReceiveInvoice = false;

        public ApplicationLibrary.ExtendedControls.TabControl masterTabControl { get { return tabControl1; } }

        public Plumber.Masters.Library.MasterTypeComboBox CbbType { get { return cbbType; } }

        public Masters()
            : base(Properties.Resources.FN_Quotations)
        {
            InitializeComponent();
            keyControl = codMaster;
        }

        #region Virtual Method

        protected override IRadarParameters GetKeyFromDocument()
        {
            return new RadarMasterParam(cbbType.GetValue<string>(), codMaster.Text);
        }

        protected override void OnAttachData()
        {
            dbManager = new dbmanagerMasters("Masters", new RadarMasterForm(RadarMasterForm.Module.Master), this);
            dbManager.AddMaster(this, PL_Masters.Name, true);
            dbManager.AddSlave(CondominSlave, false);

            myAccountingPref = new PreferencesManager<AccountingPref>(formName, null);
            AccountingPref = myAccountingPref.ReadPreference();

            CheckFiscalTaxCode = new CheckDuplicateTaxNo(dbManager.DBConnection);

            dRMasterTypeByType = new DRMasterTypeByType();
            if (dRMasterTypeByType.Find(MasterTypes.E_Condominium))
                condomType = dRMasterTypeByType.GetValue<string>(PL_MasterType.Code, 0);

            if (dRMasterTypeByType.Find(MasterTypes.E_Administrator))
            {
                string adminType = dRMasterTypeByType.GetValue<string>(PL_MasterType.Code, 0);
                rdrAdmin.AttachCodeType(adminType);
                rdrAdmin.RadarForm = new RadarMasterForm(adminType, RadarMasterForm.Module.Master);
                rdrAdmin.DescriptionControl = lblAdminDesc;
            }

            rdrTitle.RadarForm = new RadarTitles();
            rdrTitle.DescriptionControl = lblTitleDesc;

            cbbType.AttachDataReader(new RRMasterTypeForMaster());

            rRTaxCode = new RRTaxCode();
            cbbTaxCodeManager = new ComboBoxManager();
            cbbRestraintManager = new ComboBoxManager();
            cbbTaxCodeManager.AddValue(string.Empty, string.Empty);
            cbbRestraintManager.AddValue(string.Empty, string.Empty);

            rRTaxCode.Find();
            for (int t = 0; t < rRTaxCode.Count; t++)
            {
                cbbTaxCodeManager.AddValue(rRTaxCode.GetValue<string>(PL_TaxCode.Code, t), rRTaxCode.GetValue<string>(PL_TaxCode.Description, t));
                cbbRestraintManager.AddValue(rRTaxCode.GetValue<string>(PL_TaxCode.Code, t), rRTaxCode.GetValue<string>(PL_TaxCode.Description, t));
            }
            cbbTaxCodeManager.AttachTo(cbbTaxCode);
            cbbRestraintManager.AttachTo(cbbRestraint);

            dgwCondom.AutoGenerateColumns = false;
            dgwCondom.DataSource = dbManager.Dataset.Tables[CondominSlave];
            dgwCondom.AddReadOnlyColumn(PL_Masters.Code, true);
            dgwCondom.AddReadOnlyColumn(PL_Masters.Address, true);
        }

        protected override void OnBindData()
        {
            BindControl(cbbType, PL_Masters.Type, "SelectedValue", NullValue.NotSet, Findable.YES);

            BindControl(codMaster, PL_Masters.Code, Findable.YES);
            BindControl(txtCompany, PL_Masters.Description, Findable.YES);
            BindControl(ckbBlocked, PL_Masters.Blocked, "DBChecked");
            BindControl(ckbDisabled, PL_Masters.Disabled, "DBChecked");
            BindControl(txtAddress, PL_Masters.Address);
            BindControl(mtbZip, PL_Masters.ZipCode);
            BindControl(txtCity, PL_Masters.City);
            BindControl(txtCounty, PL_Masters.County);
            BindControl(txtPhone1, PL_Masters.Phone1);
            BindControl(txtPhone2, PL_Masters.Phone2);
            BindControl(txtFax, PL_Masters.Fax);
            BindControl(txtRefer1, PL_Masters.Refer1);
            BindControl(txtRefer2, PL_Masters.Refer2);
            BindControl(rdrTitle, PL_Masters.Title);
            BindControl(txtEmail, PL_Masters.Email);

            BindControl(ftbTaxNo, PL_Masters.TaxNo);
            BindControl(ftbFiscalCode, PL_Masters.FiscalCode);

            BindControl(rdrAdmin, PL_Masters.Administrator);

            BindControl(cbbTaxCode, PL_Masters.TaxCode, "SelectedValue");
            BindControl(ckbRestraint, PL_Masters.HasRestraint, "DBChecked");
            BindControl(cbbRestraint, PL_Masters.RestraintCode, "SelectedValue");

            BindControl(dgwCondom);

            BindColumn(colCode, PL_Masters.Code);
            BindColumn(colAddress, PL_Masters.Address);
        }

        protected override bool OnBeforeSave()
        {
            if (!ftbFiscalCode.CheckIsOK())
                return false;

            if (!ftbTaxNo.CheckIsOK())
                return false;

            if (isCondominium && rdrAdmin.Text == string.Empty)
            {
                MyMessageBox(string.Format(Properties.Resources.Msg_MissingCode, Properties.Resources.T_Administrator),
                Properties.Resources.Warning,
                MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }
            return base.OnBeforeSave();
        }

        protected override void OnPrepareAuxData()
        {
            rdrAdmin.UpdateDescription();
            rdrTitle.UpdateDescription();
            dbManager.RadarDocument.FilterType = null;
            dgwCondom.AutoResizeColumns();

            base.OnPrepareAuxData();
        }

        protected override bool OnBeforeAddNew()
        {
            return base.OnBeforeAddNew();
        }

        protected override bool OnAfterAddNew()
        {
            cbbType.SelectedIndex = 0;
            codMaster.Enabled = true;
            return true;
        }

        protected override void FocusOnNew()
        {
            codMaster.Focus();
        }

        protected override void OnDisableControlsForEdit()
        {
            codMaster.Enabled = false;
            cbbType.Enabled = false;

            cbbRestraint.Enabled = ckbRestraint.Checked;
        }

        protected override void OnAddSplitMenuButton()
        {
            AddSplitPreviewButton(Properties.Resources.PRNT_ENVELOPE, PRINT_ENVELOPE, PrintType.Envelope, Properties.Resources.B_Envelope);
            AddSplitPrintButton(Properties.Resources.PRNT_ENVELOPE, PRINT_ENVELOPE, PrintType.Envelope, Properties.Resources.B_Envelope);
            AddSplitPrintButton(Properties.Resources.SEND_MAIL, SEND_MAIL, PrintType.Email, Properties.Resources.B_Email);
        }

        protected override bool OnPrintDocument(PrintInfo sender, printerForm pf)
        {
            switch (sender.ReportName)
            {
                case SEND_MAIL:

                    //return PrintInvoice(pf);
                    break;

                case PRINT_ENVELOPE:
                    PrintEnvelope printEnvelope = new PrintEnvelope(pf);
                    printEnvelope.Print(lblTitleDesc.Text, txtCompany.Text, txtAddress.Text, mtbZip.Text, txtCity.Text, txtCounty.Text);
                    break;

                default:
                    return true;
            }
            return true;
        }

        #endregion

        #region Events

        private void codMaster_Validating(object sender, CancelEventArgs e)
        {
        }

        #endregion

        private void ftbTaxNo_Validating(object sender, CancelEventArgs e)
        {
            CheckFiscalTaxCode.CheckTaxNo(cbbType.GetValue<string>(), codMaster.Text, ftbTaxNo.Text);
        }

        private void ftbFiscalCode_Validating(object sender, CancelEventArgs e)
        {
            CheckFiscalTaxCode.CheckFiscalNo(cbbType.GetValue<string>(), codMaster.Text, ftbFiscalCode.Text);
        }

        private void dgwCondom_DataGridViewDoubleClickCell(object sender, ApplicationLibrary.ExtendedControls.DataGridViewDoubleClickArgs e)
        {
            if (e.ColumnName == PL_Masters.Code.Name)
            {
                Masters frm = (Masters)GlobalInfo.OpenForm("Plumber.Plumber.Masters.Forms.Masters", false);
                frm.FindRecord(new RadarMasterParam(condomType, e.CellValue));
            }
        }

        private bool Administrators_OnEnableToolbarSplitButtons(ToolStripSplitButton sender)
        {
            return true;
        }

        private void cbbType_SelectedValueChanged(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(cbbType.GetValue<string>()))
            {
                CodeMode cm = cbbType.dRMasterType.GetValue<CodeMode>(PL_MasterType.CodeMode);
                MasterTypes mt = cbbType.dRMasterType.GetValue<MasterTypes>(PL_MasterType.MasterType);
                CanReceiveInvoice = cbbType.dRMasterType.GetValue<bool>(PL_MasterType.CanReceiveInvoice);

                if (cm != CodeMode.E_IsEmpty)
                    codMaster.ReattachCodeType(cbbType.GetValue<string>());

                codMaster.Enabled = cm != CodeMode.E_IsEmpty;
                dbManager.RadarDocument.FilterType = cbbType.GetValue<string>();

                isCondominium = mt == MasterTypes.E_Condominium;
                isAdministrator = mt == MasterTypes.E_Administrator;

                cbbTaxCode.SelectedValue = cbbType.dRMasterType.GetValue<string>(PL_MasterType.TaxCode);
                cbbRestraint.SelectedValue = cbbType.dRMasterType.GetValue<string>(PL_MasterType.RestraintCode);
                ckbRestraint.Checked = cbbType.dRMasterType.GetValue<bool>(PL_MasterType.HasRestraint);
                this.Text = cbbType.Text;
            }

            rdrAdmin.Visible = isCondominium;
            lblAdminDesc.Visible = isCondominium;
            ManageTabCondominium(isAdministrator);
            ManageTabFiscalData(!isAdministrator);
        }

        private void ManageTabCondominium(bool visible)
        {
            TabPage tp = tabControl1.TabPages["tpgCondominiums"];
            if (tp == null)
            {
                if (visible)
                    tabControl1.TabPages.Add(tpgCondominiums);
            }
            else
            {
                if (!visible)
                    tabControl1.TabPages.Remove(tpgCondominiums);
            }
        }

        private void ManageTabFiscalData(bool visible)
        {
            TabPage tp = tabControl1.TabPages["tpgFiscal"];
            if (tp == null)
            {
                if (visible)
                    tabControl1.TabPages.Add(tpgFiscal);
            }
            else
            {
                if (!visible)
                    tabControl1.TabPages.Remove(tpgFiscal);
            }
        }

        private void ckbRestraint_CheckedChanged(object sender, EventArgs e)
        {
            cbbRestraint.Enabled = ckbRestraint.Checked;
            if (!cbbRestraint.Enabled)
                cbbRestraint.SelectedValue = string.Empty;
        }
    }

    #region DbManager Masters

    /// <summary>
    /// Classe derivata per gestioni particolari
    /// </summary>
    internal class dbmanagerMasters : DBManager
    {
        private const string CondominSlave = "CONDOMINIUMSLAVE";

        public dbmanagerMasters(string name, RadarForm radar, DocumentForm document)
            : base(name, radar, document)
        { }

        protected override void dAdapter_MasterRowUpdating(object sender, SqlABRowUpdatingEventArgs e)
        {
            if (e.StatementType == StatementType.Insert)
            {
                if (e.Row[PL_Masters.IsAccountingType.Name] == System.DBNull.Value)
                    e.Row[PL_Masters.IsAccountingType.Name] = 0;
            }
            base.dAdapter_MasterRowUpdating(sender, e);
        }

        protected override string CreateMasterQuery()
        {
            this.Table = new PL_Masters();
            QueryBuilder qB = new QueryBuilder();
            qB.AddSelect();
            qB.AddFrom(PL_Masters.Name);
            qB.AddCompare<bool>(PL_Masters.IsAccountingType, false);
            qB.AddCompare(PL_Masters.Code, "@p1");
            qB.AddCompare(PL_Masters.Type, "@p2");

            return qB.Query;
        }

        protected override List<SqlABParameter> CreateMasterParam()
        {
            List<SqlABParameter> PList = new List<SqlABParameter>();

            SqlABParameter sParam1 = new SqlABParameter("@p1", PL_Masters.Code);
            sParam1.Value = "";
            PList.Add(sParam1);

            SqlABParameter sParam2 = new SqlABParameter("@p2", PL_Masters.Type);
            sParam2.Value = "";
            PList.Add(sParam2);
            return PList;
        }

        protected override string CreateSlaveQuery(string name)
        {
            QueryBuilder qb = new QueryBuilder();
            if (name == CondominSlave)
            {
                string condomType = string.Empty;
                DRMasterTypeByType dRMasterTypeByType = new DRMasterTypeByType();
                if (dRMasterTypeByType.Find(MasterTypes.E_Condominium))
                    condomType = dRMasterTypeByType.GetValue<string>(PL_MasterType.Code, 0);

                qb.AddSelect();
                qb.AddFrom(PL_Masters.Name);
                qb.AddCompare(PL_Masters.Administrator, "@p3");
                qb.AddCompare<string>(PL_Masters.Type, condomType);
            }
            return qb.Query;
        }

        protected override List<SqlABParameter> CreateSlaveParam(string name)
        {
            List<SqlABParameter> PList = new List<SqlABParameter>();
            if (name == CondominSlave)
            {
                SqlABParameter p2 = new SqlABParameter("@p3", PL_Masters.Administrator);
                p2.Value = "";
                PList.Add(p2);
            }
            return PList;
        }

        protected override void SetParameters(IRadarParameters key, DBCollection collection)
        {
            if (collection.Name == PL_Masters.Name)
            {
                collection.Parameter[0].Value = key[0];
                collection.Parameter[1].Value = key[1];
            }
            else if (collection.Name == CondominSlave)
            {
                collection.Parameter[0].Value = key[0];
            }
        }
    }

    #endregion
}